//
//  ZZCRegisterTwoController.m
//  ZZC-Finance
//
//  Created by mac on 2017/5/21.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "ZZCRegisterTwoController.h"
#import "ZZCRegisterThreeController.h"

@interface ZZCRegisterTwoController ()
@property (copy, nonatomic) NSString *code;//验证码
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@end

@implementation ZZCRegisterTwoController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"正资产账户注册";
    
    [self.testTextField becomeFirstResponder];
    [self.testTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.testTextField.clearButtonMode = UITextFieldViewModeWhileEditing;

}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
//下一步
- (IBAction)nextClick {
    NSString *code = [NSString stringWithFormat:@"%@",self.code];
    if ([self.testTextField.text isEqualToString:code]) {
        ZZCRegisterThreeController *three = [ZZCRegisterThreeController new];
        three.phone = self.phone;
        three.openId = self.openId;
        three.iconUrl = self.iconUrl;
        [self.navigationController pushViewController:three animated:YES];
    }else {
        ZZCLog(@"验证码错误");
        if (!code) {
            [SVProgressHUD showInfoWithStatus:@"请输入验证码"];
        } else {
            [SVProgressHUD showInfoWithStatus:@"验证码错误"];
        }
    }
}
//获取验证码
- (IBAction)testClick {
    ZZCLog(@"获取验证码");

    NSDictionary *dict = @{@"phone":self.phone,@"type":@(1)};
    NSString *sign = [ZZCRequest getSignWithDict:dict];
    sign = [NSString md5:sign];
    NSDictionary *param = @{@"timestamp":[NSString timeStr],@"sign":sign,@"phone":self.phone,@"type":@(1)};
    [[ZZCRequest sharedNetworkTools] POST:ZZCURL_API_SENDCODE parameters:param finished:^(id  _Nullable responseObject, NSError * _Nullable error) {
        if (error) {
            ZZCLog(@"失败-%@",error);
            [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%@",error]];
        }else {
             ZZCLog(@"-%@",responseObject);
            self.code = responseObject[@"data"][@"code"];
            [SVProgressHUD showInfoWithStatus:responseObject[@"msg"]];
//            self.testTextField.text = [NSString stringWithFormat:@"%@",_code];
            if ([responseObject[@"code"]isEqual:@(200)]) {
                [self codeTimerAction];
            }
        }
    }];
}

- (void)textFieldDidChange:(UITextField *)textField{
    UITextRange *selectedRange = textField.markedTextRange;
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    if (!position) {
        // 没有高亮选择的字
        // 1. 过滤非汉字、字母、数字字符
        self.testTextField.text = [self filterCharactor:textField.text withRegex:@"[^a-zA-Z0-9\u4e00-\u9fa5]"];
        // 2. 截取
        if (self.testTextField.text.length >= 6) {
            self.testTextField.text = [self.testTextField.text substringToIndex:6];
        }
    } else {
        // 有高亮选择的字 不做任何操作
    }
}
// 过滤字符串中的非汉字、字母、数字
- (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *filterText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:filterText options:NSMatchingReportCompletion range:NSMakeRange(0, filterText.length) withTemplate:@""];
    return result;
}
// return键按下
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    if (textField.text.length < 2) {
        // 提示用户，名称长度至少为2位
        return NO;
    }
    // 设置用户名
    return YES;
}

- (void)codeTimerAction {
    __block int time = 60;
    __block UIButton *verifybutton = _codeBtn;
    verifybutton.enabled = NO;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(time<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //                verifybutton.backgroundColor = [UIColor whiteColor];
                [verifybutton setTitle:@"获取验证码" forState:UIControlStateNormal];
                verifybutton.enabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                //                verifybutton.backgroundColor = [UIColor whiteColor];
                NSString *strTime = [NSString stringWithFormat:@"已发送(%d)",time];
                [verifybutton setTitle:strTime forState:UIControlStateNormal];
                verifybutton.titleLabel.textColor = [UIColor whiteColor];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
    
}

@end
